package me.ywd.starter.command;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.repository.CrudRepository;

import java.util.Collection;

/**
 * @Author Ye_Wenda
 * @Date 8/28/2017
 */
@Slf4j
public class DbCountRunner implements CommandLineRunner {

    private Collection<CrudRepository> repositories;

    public DbCountRunner(Collection<CrudRepository> repositories) {
        this.repositories = repositories;
    }

    @Override
    public void run(String... strings) throws Exception {
        repositories.forEach(crudRepository -> {
            log.info(String.format("%s has %s entries", getRepositoryName(crudRepository.getClass()), crudRepository.count()));
        });
    }

    private static String getRepositoryName(Class crudRepositoryClass) {
        for (Class repositoryInterface : crudRepositoryClass.getInterfaces()) {
            if (repositoryInterface.getName().startsWith("me.ywd.feature.dao")) {
                return repositoryInterface.getSimpleName();
            }
        }
        return "Unknown Repository";
    }
}
